<template>
  <el-form
    ref="registerFormRef"
    :model="formData"
    :rules="formRules"
    label-width="120px"
    size="large"
    class="register-form"
  >
    <h2 class="form-title">用户注册</h2>

    <el-form-item label="手机号" label-position="top" prop="account">
      <el-input v-model="formData.account" placeholder="请输入手机号" prefix-icon="Iphone" />
    </el-form-item>

    <el-form-item label="用户名" label-position="top" prop="username">
      <el-input v-model="formData.username" placeholder="请输入用户名" prefix-icon="User" />
    </el-form-item>

    <el-form-item label="密码" label-position="top" prop="password">
      <el-input v-model="formData.password" placeholder="请输入密码" type="password" show-password prefix-icon="Lock" />
      <div class="password-strength" :class="passwordStrengthClass">密码强度: {{ passwordStrengthText }}</div>
    </el-form-item>

    <el-form-item label="确认密码" label-position="top" prop="confirmPassword">
      <el-input
        v-model="formData.confirmPassword"
        placeholder="请再次输入密码"
        type="password"
        show-password
        prefix-icon="Lock"
      />
    </el-form-item>

    <el-form-item label-position="top" prop="agreement">
      <el-checkbox v-model="formData.agreement">
        我已阅读并同意
        <el-link type="primary" @click="showAgreement">《用户协议》</el-link>
      </el-checkbox>
    </el-form-item>

    <el-form-item label-position="top">
      <el-button type="primary" class="submit-btn" :loading="loading" @click="handleSubmit">注册</el-button>
    </el-form-item>

    <!-- 添加跳转到登录页面的链接 -->
    <div class="login-link">
      已有账号？
      <el-link type="primary" @click="goToLogin">立即登录</el-link>
    </div>

    <!-- 用户协议对话框 -->
    <el-dialog v-model="agreementVisible" title="用户协议" width="70%">
      <div class="agreement-content">
        <h3>用户服务协议</h3>

        <h4>1. 账户注册</h4>
        <p>您需提供真实、准确、完整的注册信息，并妥善保管账户信息。</p>

        <h4>2. 使用规则</h4>
        <p>您承诺：</p>
        <ul>
          <li>不利用本平台从事任何非法活动</li>
          <li>不发布违法或侵权内容</li>
          <li>不干扰平台正常运行</li>
        </ul>

        <h4>3. 隐私保护</h4>
        <p>我们将保护您的个人信息。</p>

        <h4>4. 服务变更</h4>
        <p>我们有权根据业务需要调整服务内容，并将提前通知用户。</p>

        <h4>5. 免责声明</h4>
        <p>因不可抗力或必要维护导致的暂停服务，我们不承担相关责任。</p>

        <h4>6. 协议修改</h4>
        <p>我们保留修改本协议的权利。</p>

        <p class="agreement-footer">点击"我已阅读"表示您已充分理解并同意本协议全部内容。</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="agreementVisible = false">我已阅读</el-button>
      </template>
    </el-dialog>
  </el-form>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { useRouter } from 'vue-router'

  const router = useRouter()
  const emit = defineEmits(['submit'])

  // 表单引用
  const registerFormRef = ref()

  // 表单数据
  const formData = reactive({
    account: '',
    username: '',
    password: '',
    confirmPassword: '',
    agreement: false,
  })

  // 加载状态
  const loading = ref(false)

  // 用户协议对话框
  const agreementVisible = ref(false)

  // 密码强度计算
  const passwordStrength = computed(() => {
    if (!formData.password) return 0
    let strength = 0
    if (formData.password.length >= 8) strength++
    if (/[A-Z]/.test(formData.password)) strength++
    if (/[0-9]/.test(formData.password)) strength++
    if (/[^A-Za-z0-9]/.test(formData.password)) strength++
    return strength
  })

  const passwordStrengthText = computed(() => {
    const strength = passwordStrength.value
    if (strength === 0) return '无'
    if (strength === 1) return '弱'
    if (strength === 2) return '中'
    if (strength >= 3) return '强'
  })

  const passwordStrengthClass = computed(() => {
    const strength = passwordStrength.value
    if (strength === 0) return 'strength-none'
    if (strength === 1) return 'strength-weak'
    if (strength === 2) return 'strength-medium'
    if (strength >= 3) return 'strength-strong'
  })

  // 表单验证规则
  const validatePassword = (rule: any, value: string, callback: any) => {
    if (value === '') {
      callback(new Error('请输入密码'))
    } else if (value.length < 6) {
      callback(new Error('密码长度不能少于6位'))
    } else {
      callback()
    }
  }

  const validateConfirmPassword = (rule: any, value: string, callback: any) => {
    if (value === '') {
      callback(new Error('请再次输入密码'))
    } else if (value !== formData.password) {
      callback(new Error('两次输入密码不一致'))
    } else {
      callback()
    }
  }

  const validateAgreement = (rule: any, value: boolean, callback: any) => {
    if (!value) {
      callback(new Error('请同意用户协议'))
    } else {
      callback()
    }
  }

  const formRules = reactive({
    account: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号',
        trigger: 'blur',
      },
    ],
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 16, message: '用户名长度应为2-16个字符', trigger: 'blur' },
    ],
    password: [{ validator: validatePassword, trigger: 'blur' }],
    confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
    agreement: [{ validator: validateAgreement, trigger: 'change' }],
  })

  // 提交表单
  const handleSubmit = async () => {
    if (!registerFormRef.value) return

    try {
      const isValid = await registerFormRef.value.validate()
      if (!isValid) return

      loading.value = true

      // 准备提交数据
      const registerData = {
        account: formData.account,
        username: formData.username,
        password: formData.password,
      }

      // 触发注册逻辑（由父组件处理）
      emit('submit', registerData)
    } catch (error) {
      console.error('表单验证失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 显示用户协议
  const showAgreement = () => {
    agreementVisible.value = true
  }

  // 跳转到登录页
  const goToLogin = () => {
    router.push('/login')
  }
</script>

<style scoped>
  .register-form {
    width: 80%;
    max-width: 480px;
    padding: 20px;
  }

  .form-title {
    text-align: center;
    margin-bottom: 36px;
    color: #333;
    font-weight: 600;
  }

  .submit-btn {
    width: 100%;
    height: 50px;
    font-size: 16px;
    margin-top: 10px;
  }

  .login-link {
    text-align: center;
    margin-top: 20px;
    color: #666;
  }

  .password-strength {
    font-size: 12px;
    margin-top: 8px;
  }

  .strength-none {
    color: #999;
  }

  .strength-weak {
    color: #f56c6c;
  }

  .strength-medium {
    color: #e6a23c;
  }

  .strength-strong {
    color: #67c23a;
  }

  .agreement-content {
    max-height: 60vh;
    overflow-y: auto;
    padding: 0 20px;
  }
</style>
